package sync

import (
	"api/app/wms/models"
	"api/config"
	"api/libs/errs"
	sync "api/public/model-sync"
	"encoding/json"
	"gitee.com/dreamwood/ez"
)

func init() {
	targetServiceId := config.GetService().Dependence["srcDepartment"]

	errs.Try(sync.GetMS().SubInitFeed(targetServiceId, "Department", func(data *sync.ModelData) error {
		//处理数据初始化的请求
		return createOrUpdate(data)
	}))
	errs.Try(sync.GetMS().SubCrud(targetServiceId, "Department", "Department", func(data *sync.ModelData) error {
		return createOrUpdate(data)
	}))
}

func createOrUpdate(data *sync.ModelData) error {
	ez.Debug("开始处理同步事件")
	crud := models.NewDepartmentCrud()
	dept := new(models.Department)
	if errs.Try(json.Unmarshal(data.Data, dept)) {
		return nil
	}
	switch data.Crud {
	case sync.CRUD_D:
		task := &models.Department{Id: dept.Id}
		errs.Try(crud.Factory.Delete(task))
	//删除
	default:
		find, _ := crud.Find(dept.Id)
		task := new(models.Department)
		task.Id = dept.Id
		task.Name = dept.Name
		if find.Id > 0 {
			task.Save()
		} else {
			errs.Try(crud.Factory.Create(task))
		}
	}
	return nil
}
